package P3排序算法;

import java.util.Arrays;

//堆排序
public class HeapSort {
    public static void main(String[] args) {
        int[] arr = {3, 1, 2, 6, 5, 9, 8, 4, 7};
        heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }
    private static int len = 0;
    public static void heapSort(int[] arr) {
        len = arr.length;
        //1.对arr进行堆化处理
        heapify(arr);
        //2.将每个区间的最大值与末尾交换 末尾下沉
        //O(NlogN)
        for (int i = arr.length - 1; i >= 0; i--) {
            swap(arr, 0, i);
            len--;
            siftDown(arr,0);
        }
    }

    private static void heapify(int[] arr) {
        //O(N)   O(NlogN)
        for (int i = arr.length - 1; i >= 0; i--) {
            siftDown(arr, i);
        }
    }
    //O(logN)
    private static void siftDown(int[] arr, int k) {
        while (2 * k + 1 < len) {
            int j = 2 * k + 1;
            if (j + 1 < len && arr[j + 1] > arr[j]) {
                j = j + 1;
            }
            if (arr[k] < arr[j]) {
                swap(arr, k, j);
                k = j;
            } else {
                break;
            }
        }
    }

    private static void swap(int[] arr, int k, int j) {
        int temp = arr[k];
        arr[k] = arr[j];
        arr[j] = temp;
    }
}